import path from "path";
import md5File from "md5-file";
import cos from "./cos";
import fs from "fs";

if (!fs.existsSync("./upload")) {
  fs.mkdirSync("./upload");
}

const uploadDir = "q-ice/";

export async function uploadOne(file, body = {}) {
  const filePath = path.join(process.cwd(), file.path);
  let name = body.path_name;
  if (!name) {
    name = md5File.sync(filePath) + path.extname(file.originalname);
    name = path.join(body.dir || uploadDir, name);
  }
  let data;
  try {
    // todo: name为自定义时，可存储name和fileHash记录来查询name
    await cos.head(name);
    const { Region, Bucket } = cos.options;
    data = {
      url: `https://${Bucket}.cos.${Region}.myqcloud.com/${name}`,
      head: true,
    };
  } catch (error) {
    // console.log(error.message);
  }
  if (!data) {
    const { url } = await cos.put(name, fs.createReadStream(filePath));
    data = {
      url,
    };
  }
  fs.unlink(filePath, (err) => {
    if (err) console.log(err);
  });
  return data;
}

export async function uploadMulti(files, query = {}) {
  const res = [];
  for (const file of files) {
    const data = await uploadOne(file, query);
    res.push(data);
  }
  return res;
}
